﻿using UnityEngine;

using System.Collections;
using System.IO;
using System.Threading;
using System.Net;

public class wishDownload : MonoBehaviour
{
    /// <summary>
    /// URL下载路径
    /// </summary>
    private string wish_DownLoadURL;
    /// <summary>
    /// 临时存放地址
    /// </summary>
    private string wish_Temporarypath;
    /// <summary>
    /// 完整应用存放地址
    /// </summary>
    private string wish_Installpath;
    /// <summary>
    /// 存储文件名
    /// </summary>
    private string wish_FileName;
    /// <summary>
    /// 临时存放后缀。要区别于正式后缀名，否则下载中断后无法继续下载。
    /// </summary>
    private string wish_Temporarysuffix;
    /// <summary>
    /// 正式后缀名，例.apk
    /// </summary>
    private string wish_Filesuffix;
    private Thread wish_Thread;

    string strUrl = "http://dlsw.baidu.com/sw-search-sp/soft/ca/13442/Thunder_dl_7.9.42.5050.1449557123.exe";
    void Start()
    {
        //设置并发数，默认为2，容易异常
        System.Net.ServicePointManager.DefaultConnectionLimit = 512;
        DownloadStart(strUrl, "poda", Application.dataPath, Application.dataPath, ".temp", ".exe");
    }

    public void DownloadStart(string URL, string FileName, string

    Temporarypath, string Installpath, string Temporarysuffix, string

    Filesuffix)
    {
        wish_DownLoadURL = URL;
        wish_FileName = FileName;
        wish_Temporarypath = Temporarypath;
        wish_Installpath = Installpath;
        wish_Temporarysuffix = Temporarysuffix;
        wish_Filesuffix = Filesuffix;

        CheckFolder(wish_Temporarypath);
        CheckFolder(wish_Installpath);

        CheckFile(wish_FileName, URL);
    }
    /// <summary>
    /// 判断路径是否存在
    /// </summary>
    /// <param name="path"></param>
    void CheckFolder(string path)
    {
        if (Directory.Exists(path) == false)
        {
            Directory.CreateDirectory(path);
        }
    }
    /// <summary>
    /// 判断完整文件是否存在
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="url"></param>
    public void CheckFile(string fileName, string url)
    {
        if (File.Exists(wish_Installpath + "/" + fileName + wish_Filesuffix))
        {
            // 文件存在，不用下载
        }
        else
        {
            DownFile(fileName, url);
        }
    }

    void DownFile(string fileName, string url)
    {
        DownThread DW = new DownThread(fileName + wish_Temporarysuffix,

        wish_Temporarypath + "/" + fileName + wish_Temporarysuffix, url,

        wish_Filesuffix, wish_Temporarysuffix, wish_Temporarypath,

        wish_Installpath);

        wish_Thread = new Thread(new ThreadStart(DW.Down));

        wish_Thread.Start();
    }

    class DownThread
    {
        string name;
        string url;
        string fileName;
        long DownloadByte;
        string Filesuffix;
        string Temporarysuffix;
        string Temporarypath;
        string Installpath;

        public DownThread(string fileName, string name, string url, string

        Filesuffix, string Temporarysuffix, string Temporarypath, string

        Installpath)
        {
            this.fileName = fileName;
            this.name = name; //临时存放名
            this.url = url;
            this.Filesuffix = Filesuffix;
            this.Temporarysuffix = Temporarysuffix;
            this.Temporarypath = Temporarypath;
            this.Installpath = Installpath;
        }

        public void Down()
        {
            DownloadByte = 0;
            long lStartPos = 0;
            FileStream fs;

            if (File.Exists(name))
            {
                fs = File.OpenWrite(name);
                lStartPos = fs.Length; //取得文件长度，继续下载
                fs.Seek(lStartPos, SeekOrigin.Current);
            }
            else
            {
                fs = new FileStream(name, FileMode.Create);
                lStartPos = 0;
            }

            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                if (lStartPos > 0)
                {
                    request.AddRange((int)lStartPos);
                }
                Stream ns = request.GetResponse().GetResponseStream();
                byte[] nbytes = new byte[8192];
                int nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 8192);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);

                    nReadSize = ns.Read(nbytes, 0, 8192);
                }

                string changeName;
                changeName = name.Substring(0, name.LastIndexOf("."));
                changeName += Filesuffix;
                changeName = changeName.Replace(Temporarypath, Installpath);

                fs.Close();

                ns.Close();

                if (File.Exists(name))
                {
                    Debug.Log(name);
                    Debug.Log(changeName);

                    try
                    {
                        File.Move(name, changeName);
                    }
                    catch (System.Exception e)
                    {
                        Debug.Log(e.ToString());
                        throw;
                    }
                }
            }
            catch
            {
                fs.Close();
            }
        }
    }
}